    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.click.app.webapp.action;

import com.click.app.model.Category;
import com.click.app.model.FeatureProduct;
import com.click.app.model.FeatureProductName;
import com.click.app.model.LabelValue;
import com.click.app.model.Product;
import com.click.app.model.ProductType;
import com.click.app.model.RequestClient;
import com.click.app.model.StorageProduct;
import com.click.app.model.User;
import com.click.app.service.CartManager;
import com.click.app.service.FeatureProductManager;
import com.click.app.service.FeatureProductNameManager;
import com.click.app.service.CategoryManager;
import com.click.app.service.ProductManager;
import com.click.app.service.ProductTypeManager;
import com.click.app.service.RequestClientManager;
import com.click.app.service.StorageProductManager;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import org.apache.struts2.ServletActionContext;

/**
 *
 * @author orgale
 */
public class ProductTypeAction extends BaseAction {

    private ProductTypeManager productTypeManager;
    private ProductManager productManager;
    private CategoryManager categoryManager;
    private RequestClientManager requestClientManager;
    //private GenericManager<PurchaseDetail, Long> purchaseDetailManager;
    private FeatureProductManager featureProductManager;
    private FeatureProductNameManager featureProductNameManager;
    private StorageProductManager storageProductManager;
    private List productTypes;
    private ProductType productType;
    private Long id;
    private Long idMeasureUnit;
    private List<FeatureProduct> featureProductsDescriptions;
    private Long idD;
    private String featureProductName;
    private String featureProductDescription;
    private FeatureProduct featureProduct;
    private Integer featureProductIndex;
    private Long idFeatureProduct;
    private List<FeatureProduct> featureProductList;
    private List<FeatureProduct> featureProductsList;
    private String limit;
    private CartManager cartManager;
    private RequestClient requestClient;
    private File file;
    private String fileContentType;
    private String fileFileName;
    private String name;
    private InputStream inputStream;
    private Set<String> productOpions;
    private Set<String> productOptionsPicked;
    private List<LabelValue> productListLeft;
    private List<LabelValue> productListRight;
    private Set<LabelValue> productListLeftV;
    private Set<LabelValue> productListRightV;

    public void setCategoryManager(CategoryManager categoryManager) {
        this.categoryManager = categoryManager;
    }

    public void setRequestClientManager(RequestClientManager requestClientManager) {
        this.requestClientManager = requestClientManager;
    }

    public void setCartManager(CartManager cartManager) {
        this.cartManager = cartManager;
    }

    public void setProductManager(ProductManager productManager) {
        this.productManager = productManager;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public ProductType getProductType() {
        return productType;
    }

    public void setProductType(ProductType productType) {
        this.productType = productType;
    }

    public List<Category> getCategorys() {
        return categoryManager.getAll();
    }

    public StorageProduct findStorageProduct(ProductType m) {
        for (StorageProduct st : storageProductManager.getAll()) {
            if (st.getProduct().equals(m)) {
                return st;
            }
        }
        return null;
    }

    public String delete() {
        try {
            //removin category reference
            for (Category c : categoryManager.getAll()) {
                if (c.getProductTypes().contains(productTypeManager.get(productType.getId()))) {
                    c.getProductTypes().remove(productTypeManager.get(productType.getId()));
                }
            }

            //removin product type
            System.out.println("remove product type");
            productTypeManager.remove(productType.getId());
            saveMessage(getText("productType.deleted"));
            return SUCCESS;
        } catch (Exception e) {
            errorMessage(getText("generalEerror"));
            return SUCCESS;

        }
    }

    public boolean parentsFree(Product p) {
        boolean resp = true;
        for (ProductType pt : productTypeManager.getAll()) {
            for (Product pe : pt.getProducts()) {
                if (pe.getId().equals(p.getId())) {
                    resp = false;
                }
            }
        }
        return resp;
    }

    public List<LabelValue> getProductNamesAndValues() {
        List<LabelValue> namesAndValues = new ArrayList<LabelValue>();
        List<Product> ps = productManager.getAll();
        for (Product p : ps) {
            System.out.println("parentsfree: " + parentsFree(p));
            if (parentsFree(p)) {
                namesAndValues.add(new LabelValue(p.getNameLang(), p.getId().toString()));
            }
        }
        return namesAndValues;
    }

    public LabelValue getPos(List<LabelValue> lp, Product pt) {
        for (LabelValue lv : lp) {
            if ((pt.getId().toString().matches(lv.getValue()))) {
                return lv;
            }
        }
        return null;
    }

    public String edit() throws Exception {
        System.out.println("Editing productType...");

        if (id != null) {
            System.out.println("Editing existing productType...");

            productType = productTypeManager.get(id);

            productListLeft = getProductNamesAndValues();
            productListRight = new ArrayList<LabelValue>();
            System.out.println("products in producttypes: " + productType.getProducts().size());
            for (Product p : productType.getProducts()) {
                productListRight.add(new LabelValue(p.getNameLang(), p.getId().toString()));
                productListLeft.remove(getPos(getProductNamesAndValues(), p));
            }
            getSession().setAttribute("products", productType.getProducts());
            getSession().setAttribute("productType", productType);
        } else {
            System.out.println("Editing new productType...");
            productListLeft = getProductNamesAndValues();
            productListRight = new ArrayList<LabelValue>();
            productType = new ProductType();
        }
        System.out.println("productType to be edited: " + productType);
        return SUCCESS;
    }

    public boolean haveCart(User user) {
        boolean resp = false;
        if (!cartManager.findCartByUser(user).isEmpty()) {
            resp = true;
        }
        return resp;
    }

    public int findIndex(Long id) {
        int i = -1;
        featureProductList = (List<FeatureProduct>) getSession().getAttribute("featureProductList");
        for (FeatureProduct d : featureProductList) {
            if (d.getId().equals(id)) {
                i = featureProductList.indexOf(d);
            }
        }
        System.out.println("retornando index: " + i);
        return i;
    }

    public List<LabelValue> getBooleans() {
        List<LabelValue> b = new ArrayList<LabelValue>();
        LabelValue t = new LabelValue(getText("true.available"), "true");
        LabelValue f = new LabelValue(getText("false.unavailable"), "false");
        b.add(t);
        b.add(f);
        return b;
    }

    public boolean validationPasses() {
        Float aux = 0.0f;
        boolean vp = true;
        if (productType.getName() == null || productType.getName().matches("")) {
            errorMessage("Required field, name.");
            vp = false;
        }
        if (productType.getNameEs() == null || productType.getNameEs().matches("")) {
            errorMessage("Required field, name (es).");
            vp = false;
        }

        return vp;
    }

    public String afp() {
        System.out.println("currentProduct: " + productType);
        getSession().setAttribute("productType", productType);

        return "afp";
    }

    public String save() throws Exception {
        System.out.println("Saving productType...:" + productType);

        if (cancel != null) {
            System.out.println("currentProduct: " + productType);
            getSession().setAttribute("productType", productType);
            return CANCEL;
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (productType.getId() == null);

        productType.setProducts(new ArrayList<Product>());
        if (getProductOptionsPicked() != null) {
            for (String s : getProductOptionsPicked()) {
                Product pt = productManager.get(new Long(Integer.parseInt(s)));
                productType.getProducts().add(pt);

            }
        }


        if (file == null) {
            String path = ServletActionContext.getServletContext().getRealPath("/images");
            file = new File(path + "/403.jpg");
        }
        InputStream is = new FileInputStream(file);
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        is.close();
        productType.setImageProductType(bytes);

        if (validationPasses()) {
            //productType.setImageProductType(null);
            productType = productTypeManager.save(productType);
        } else {
            edit();
            return ERROR;
        }

        String key = (isNew) ? "productType.added" : "productType.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }

    public void setProductTypeManager(ProductTypeManager productTypeManager) {
        this.productTypeManager = productTypeManager;
    }

    public void setFeatureProductManager(FeatureProductManager featureProductManager) {
        this.featureProductManager = featureProductManager;
    }

    public void setFeatureProductNameManager(FeatureProductNameManager featureProductNameManager) {
        this.featureProductNameManager = featureProductNameManager;
    }

    public void setStorageProductManager(StorageProductManager storageProductManager) {
        this.storageProductManager = storageProductManager;
    }

    public List getProductTypes() {
        return productTypes;
    }

    public String list() {
        getSession().setAttribute("products", null);
        System.out.println("ProductTypeAction -> list()");
        productTypes = productTypeManager.getAll();
        System.out.println("ProductTypeAction -> end list()");
        return SUCCESS;
    }

    public InputStream getInputStream() {
        System.out.println("ProductTypeAction -> getInputStream() -> ");
        inputStream = null;
	getResponse().resetBuffer();
	
        if (id != null) {
            productType = productTypeManager.get(id);
        }
        if (getSession().getAttribute("productType") != null) {
            productType = (ProductType) getSession().getAttribute("productType");
        }

        if (productType != null && productType.getImageProductType() != null) {
            inputStream = new ByteArrayInputStream(productType.getImageProductType());
        } else {
                try {
                    String path = ServletActionContext.getServletContext().getRealPath("/images");
                    file = new File(path + "/403.jpg");
                    InputStream is = new FileInputStream(file);
                    long length = file.length();
                    if (length > Integer.MAX_VALUE) {
                        // File is too large
                    }

                    byte[] bytes = new byte[(int) length];
                    int offset = 0;
                    int numRead = 0;
                    while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                        offset += numRead;
                    }
                    if (offset < bytes.length) {
                        throw new IOException("Could not completely read file " + file.getName());
                    }
                    is.close();
                    inputStream = new ByteArrayInputStream(bytes);
                } catch (IOException ioex) {
                    ioex.printStackTrace();
                }
                System.out.println("inputStream "+inputStream);
        }
        System.out.println("ProductTypeAction -> end getInputStream()");
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    /**
     * @return the idMeasureUnit
     */
    public Long getIdMeasureUnit() {
        return idMeasureUnit;
    }

    /**
     * @param idMeasureUnit the idMeasureUnit to set
     */
    public void setIdMeasureUnit(Long idMeasureUnit) {
        this.idMeasureUnit = idMeasureUnit;
    }

    /**
     * @return the featureProduct
     */
    public FeatureProduct getFeatureProduct() {
        return featureProduct;
    }

    /**
     * @param featureProduct the featureProduct to set
     */
    public void setFeatureProduct(FeatureProduct featureProduct) {
        this.featureProduct = featureProduct;
    }

    /**
     * @return the featureProductIndex
     */
    public Integer getFeatureProductIndex() {
        return featureProductIndex;
    }

    /**
     * @param featureProductIndex the featureProductIndex to set
     */
    public void setFeatureProductIndex(Integer featureProductIndex) {
        this.featureProductIndex = featureProductIndex;
    }
    private String lst;
    private List lstList = null;
    private List lstList2 = null;

    public List getLstList() {
        System.out.println("Obteining list");
        System.out.println("LIST: " + lstList);
        return lstList;
    }

    public void setLstList(List lstList) {
        this.lstList = lstList;
    }

    public String getLst() {
        return lst;
    }

    public void setLst(String lst) {
        this.lst = lst;
    }

    public List<FeatureProduct> getFeatureProductList() {
        return (List<FeatureProduct>) getSession().getAttribute("featureProductList");
    }

    public List<FeatureProduct> getFeatureProductsList() {
        return featureProductManager.findFeatureProducts();
    }

    /**
     * @return the idD
     */
    public Long getIdD() {
        return idD;
    }

    /**
     * @param idD the idD to set
     */
    public void setIdD(Long idD) {
        this.idD = idD;
    }
    private List characters;

    public String ajaxSelect() {

        System.out.println("EXECUTE!!!");

        idD = Long.parseLong(getRequest().getParameter("idD"));

        System.out.println("idD: " + idD);

        FeatureProduct dis = featureProductManager.get(idD);
        if (dis == null) {
            dis = new FeatureProduct();
        }
        featureProductsDescriptions = featureProductManager.findFeatureProductsName(dis.getName());
        System.out.println("featureProduct descriptions: " + featureProductsDescriptions.size());
        getSession().setAttribute("featureProductDescriptions", featureProductsDescriptions);
        return SUCCESS;
    }

    public String ajaxS() {
        // Get a list of characters associated with the select TV show

        System.out.println("EXECUTE!!!");

        idD = Long.parseLong(getRequest().getParameter("idD"));

        System.out.println("idD: " + idD);

        FeatureProduct dis = featureProductManager.get(idD);
        if (dis == null) {
            dis = new FeatureProduct();
        }
        featureProductsDescriptions = featureProductManager.findFeatureProductsName(dis.getName());
        return SUCCESS;
    }

    // End execute()
    // This method returns a list of characters for a given TV show.  If no TV
    // show is selected, i.e., initial page view, am empty ArrayList is returned.
    /**
     * @return the characters
     */
    public List getCharacters() {
        System.out.print("getting characters...");
        return characters;
    }

    /**
     * @param characters the characters to set
     */
    public void setCharacters(List characters) {
        this.characters = characters;
    }

    /**
     * @return the featureProductsDescription
     */
    public List<FeatureProduct> getFeatureProductsDescriptions() {
        return featureProductsDescriptions;
    }

    /**
     * @param featureProductsDescription the featureProductsDescription to set
     */
    public void setFeatureProductsDescriptions(List<FeatureProduct> featureProductsDescription) {
        this.featureProductsDescriptions = featureProductsDescription;
    }

    /**
     * @param featureProductList the featureProductList to set
     */
    public void setFeatureProductList(List<FeatureProduct> featureProductList) {
        this.featureProductList = featureProductList;
    }

    /**
     * @return the featureProductDescription
     */
    public String getFeatureProductDescription() {
        return featureProductDescription;
    }

    /**
     * @param featureProductDescription the featureProductDescription to set
     */
    public void setFeatureProductDescription(String featureProductDescription) {
        this.featureProductDescription = featureProductDescription;
    }

    /**
     * @param featureProductsList the featureProductsList to set
     */
    public void setFeatureProductsList(List<FeatureProduct> featureProductsList) {
        this.featureProductsList = featureProductsList;
    }

    /**
     * @return the idFeatureProduct
     */
    public Long getIdFeatureProduct() {
        return idFeatureProduct;
    }

    /**
     * @param idFeatureProduct the idFeatureProduct to set
     */
    public void setIdFeatureProduct(Long idFeatureProduct) {
        this.idFeatureProduct = idFeatureProduct;
    }

    public String helpList() {
        return SUCCESS;
    }

    public String help() {
        return SUCCESS;
    }

    /**
     * @return the limit
     */
    public String getLimit() {
        System.out.println("limitg: " + limit);
        return limit;
    }
    private String defaultItem;
    private String doubleDefaultItem;

    /**
     * @param limit the limit to set
     */
    public void setLimit(String limit) {
        this.limit = limit;
    }

    /**
     * @return the featureProductName
     */
    public String getFeatureProductName() {
        return featureProductName;
    }

    /**
     * @param featureProductName the featureProductName to set
     */
    public void setFeatureProductName(String featureProductName) {
        this.featureProductName = featureProductName;
    }

    public List<FeatureProductName> getFeatureProductNames() {
        return featureProductNameManager.getAll();
    }

    /**
     * @return the defaultItem
     */
    public String getDefaultItem() {
        return defaultItem;
    }

    /**
     * @param defaultItem the defaultItem to set
     */
    public void setDefaultItem(String defaultItem) {
        this.defaultItem = defaultItem;
    }

    /**
     * @return the doubleDefaultItem
     */
    public String getDoubleDefaultItem() {
        return doubleDefaultItem;
    }

    /**
     * @param doubleDefaultItem the doubleDefaultItem to set
     */
    public void setDoubleDefaultItem(String doubleDefaultItem) {
        this.doubleDefaultItem = doubleDefaultItem;
    }

    public FeatureProduct getFeatureProductWithNameAndDescription(String n, String v) {
        FeatureProduct d = null;
        for (FeatureProduct di : featureProductManager.getAll()) {
            if ((di.getDescription().matches(v)) && (di.getName().matches(n))) {
                d = di;
            }
        }
        return d;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public List getLstList2() {
        return lstList2;
    }

    public void setLstList2(List lstList2) {
        this.lstList2 = lstList2;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the requestClient
     */
    public RequestClient getRequestClient() {
        return requestClient;
    }

    /**
     * @param requestClient the requestClient to set
     */
    public void setRequestClient(RequestClient requestClient) {
        this.requestClient = requestClient;
    }

    /**
     * @return the productOpions
     */
    public Set<String> getProductOpions() {
        return productOpions;
    }

    /**
     * @param productOpions the productOpions to set
     */
    public void setProductOpions(Set<String> productOpions) {
        this.productOpions = productOpions;
    }

    /**
     * @return the productOptionsPicked
     */
    public Set<String> getProductOptionsPicked() {
        return productOptionsPicked;
    }

    /**
     * @param productOptionsPicked the productOptionsPicked to set
     */
    public void setProductOptionsPicked(Set<String> productOptionsPicked) {
        this.productOptionsPicked = productOptionsPicked;
    }

    /**
     * @return the productListLeft
     */
    public List<LabelValue> getProductListLeft() {
        return productListLeft;
    }

    /**
     * @param productListLeft the productListLeft to set
     */
    public void setProductListLeft(List<LabelValue> productListLeft) {
        this.productListLeft = productListLeft;
    }

    /**
     * @return the productListRight
     */
    public List<LabelValue> getProductListRight() {
        return productListRight;
    }

    /**
     * @param productListRight the productListRight to set
     */
    public void setProductListRight(List<LabelValue> productListRight) {
        this.productListRight = productListRight;
    }

    /**
     * @return the productListLeftV
     */
    public Set<LabelValue> getProductListLeftV() {
        return productListLeftV;
    }

    /**
     * @param productListLeftV the productListLeftV to set
     */
    public void setProductListLeftV(Set<LabelValue> productListLeftV) {
        this.productListLeftV = productListLeftV;
    }

    /**
     * @return the productListRightV
     */
    public Set<LabelValue> getProductListRightV() {
        return productListRightV;
    }

    /**
     * @param productListRightV the productListRightV to set
     */
    public void setProductListRightV(Set<LabelValue> productListRightV) {
        this.productListRightV = productListRightV;
    }
}
